package com.shaoshaohuo.app.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.FaceMarketHeadVpAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.Baoxian;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.FocusImage;
import com.shaoshaohuo.app.entity.MainEntity;
import com.shaoshaohuo.app.entity.News;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.LoginActivity;
import com.shaoshaohuo.app.ui.MainTabActivity;
import com.shaoshaohuo.app.ui.MessageCenterActivity;
import com.shaoshaohuo.app.ui.WebBrowserActivity;
import com.shaoshaohuo.app.ui.ec.MyFragmentActivity;
import com.shaoshaohuo.app.ui.shipper.FindCarActivity;
import com.shaoshaohuo.app.ui.shipper.MyOrderTailAfterActivity;
import com.shaoshaohuo.app.ui.shipper.SendGoodsActivity;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.view.CirclePageIndicator;
import com.shaoshaohuo.app.view.TopbarView;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @author: yusonglin
 * @类 说 明:货主首页
 * @创建时间：2015年7月27日 下午2:13:10
 */
public class UserFragment extends Fragment implements OnClickListener {

    private View mContentView;

    private TopbarView mTopbarView;
    private CirclePageIndicator mIndicator;
    private ViewPager mHeaderViewPager;

    private View mFahuoLayout;
    private View mZhaocheLayout;
    private View mOrderGenzongLayout;
    private View mEcLayout;

    private Button mKefuButton;

    private String mArgument;
    public static final String ARGUMENT = "argument";

    public static UserFragment newInstance(String argument) {
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT, argument);
        UserFragment contentFragment = new UserFragment();
        contentFragment.setArguments(bundle);
        return contentFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null)
            mArgument = bundle.getString(ARGUMENT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.fragment_shipper, null);

            initView();
            setUpView();
            requestMainImages();
        } else {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeView(mContentView);
            }
        }
        return mContentView;
    }

    private void initView() {
        mTopbarView = (TopbarView) mContentView.findViewById(R.id.topbar);
        mTopbarView.setCenterText("我是货主");
        if (getActivity() instanceof MainTabActivity) {
            mTopbarView.setLeftImage(R.drawable.navbar_menu, "");
            mTopbarView.setLeftClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ((MainTabActivity) getActivity()).toggle();
                }
            });
        } else if (getActivity() instanceof MyFragmentActivity) {
            mTopbarView.setLeftView(true, true);
        }
        mTopbarView.setRightImage(R.drawable.icon_message_ad);
        mTopbarView.setRightClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (AccountManager.isLogin()) {
                    Intent intent = new Intent(getActivity(), MessageCenterActivity.class);
                    getActivity().startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });

        mHeaderViewPager = (ViewPager) mContentView.findViewById(R.id.viewpager_main1_header);
        mIndicator = (CirclePageIndicator) mContentView.findViewById(R.id.cpi_face_viewpager);

        mFahuoLayout = mContentView.findViewById(R.id.layout_woyaofahuo);
        mZhaocheLayout = mContentView.findViewById(R.id.layout_woyaozhaoche);
        mOrderGenzongLayout = mContentView.findViewById(R.id.layout_dingdangenzong);
        mEcLayout = mContentView.findViewById(R.id.layout_ec);
        //
        mKefuButton = (Button) mContentView.findViewById(R.id.button_kefu);
    }

    private void setUpView() {
        mFahuoLayout.setOnClickListener(this);
        mZhaocheLayout.setOnClickListener(this);
        mOrderGenzongLayout.setOnClickListener(this);
        mEcLayout.setOnClickListener(this);
        mKefuButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_woyaofahuo:
                if (AccountManager.checkUserAuth(getActivity())) {
                    Intent intent1 = new Intent(getActivity(), SendGoodsActivity.class);
                    getActivity().startActivity(intent1);
                }
                break;
            case R.id.layout_woyaozhaoche:
//    		if (AccountManager.checkAuth(getActivity())) {
                Intent intent = new Intent(getActivity(), FindCarActivity.class);
                getActivity().startActivity(intent);
//    		} 
                break;
            case R.id.layout_ec:
                //        	if(getActivity() instanceof MainTabActivity){
                //        		fd
                //            }else if(getActivity() instanceof MyFragmentActivity){

//    		if (AccountManager.checkAuth(getActivity())) {
                Intent intent3 = new Intent(getActivity(), MyFragmentActivity.class);
                intent3.putExtra(ExtraName.id, 3);
                getActivity().startActivity(intent3);
//    		}
                //            }
                break;
            case R.id.layout_dingdangenzong:
                if (AccountManager.isLogin()) {
                    Intent intent2 = new Intent(getActivity(), MyOrderTailAfterActivity.class);
                    getActivity().startActivity(intent2);
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            // case R.id.layout_my_orders:
            // Intent intent3 = new Intent(getActivity(),CarOwnerInfoActivity.class);
            // getActivity().startActivity(intent3);
            // break;
            // case R.id.layout_news:
            // Intent intent4 = new Intent(getActivity(),NewsActivity.class);
            // getActivity().startActivity(intent4);
            // break;
            case R.id.button_kefu:
                DeviceHelper.callPhone(getActivity(), "4000011857");
                break;
        }
    }

    private void requestMainImages() {

        // MainImagesEntity entity = new MainImagesEntity();
        // List<String> list = new ArrayList<>();
        // list.add("http://a.hiphotos.baidu.com/image/pic/item/d0c8a786c9177f3e77b960dd73cf3bc79e3d5654.jpg");
        // list.add("http://img.wallpapersking.com/800/2015-4/2015042207278.jpg");
        // list.add("http://img.wallpapersking.com/800/2015-4/2015042207279.jpg");
        // list.add("http://img.wallpapersking.com/800/2015-3/2015031907131.jpg");
        // list.add("http://img.wallpapersking.com/800/2015-3/2015031907132.jpg");
        // entity.setImages(list);
        // setMainImages(entity);

        RequestService.getInstance().mainIndex(getActivity(), 1 + "", MainEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {

                if (resultData.isOk()) {
                    MainEntity result = (MainEntity) resultData;
                    setMainImages(result.getData().getFocus());
                    setNews(result.getData().getNews());
                    saveBx(result.getData().getBx());
                } else {
                    ToastUtil.toast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                try {
                    ToastUtil.toast(R.string.please_check_network);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    protected void saveBx(Baoxian bx) {
        AccountManager.saveBaoxian(bx);
    }

    protected void setNews(List<News> news) {
    }

    protected void setMainImages(List<FocusImage> result) {
        pagerSize = result.size();
        HeaderVpAdapter adapter = new HeaderVpAdapter(getActivity(), result, 1, result.size());
        mHeaderViewPager.setAdapter(adapter);
        mIndicator.setViewPager(mHeaderViewPager);
        mIndicator.notifyDataSetChanged();

        startPagerTask();
    }

    private class HeaderVpAdapter extends FaceMarketHeadVpAdapter<FocusImage> {

        public HeaderVpAdapter(Context context, List<FocusImage> array, int previewCount, int maxListSize) {
            super(context, array, previewCount, maxListSize);
        }

        @Override
        public Object getView(ViewGroup container, final FocusImage data, int position) {

            View view = View.inflate(mContext, R.layout.view_main1_header_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView_main1_header_item);
            switch (position) {
                // case 0:
                // //
                // imageView.setImageResource(R.drawable.face_market_disney_detail_top);
                // LoadUtils.getInstance(mContext).loadImage(imageView,
                // R.drawable.face_market_disney_detail_top);
                // break;
                // case 1:
                // //
                // imageView.setImageResource(R.drawable.face_market_vn_detail_top);
                //
                // LoadUtils.getInstance(mContext).loadImage(imageView,
                // R.drawable.face_market_vn_detail_top);
                //
                // break;
                default:
                    // FaceHelper.displayImageView(imageView,
                    // FaceHelper.getImageServerUrl(Data),
                    // IUtil.getBigPicDisplayImageOptions());
                    // LoadUtils.getInstance(mContext).loadImage(imageView,
                    // FaceHelper.getImageServerUrl(Data));
                    break;
            }

            // LoadUtils.getInstance().loadImage(imageView, Data.getBigimg(), new
            // LoadImageListener() {
            //
            // @Override
            // public void onStart(ImageView arg0, String arg1) {
            // // TODO Auto-generated method stub
            //
            // }
            //
            // @Override
            // public void onResult(ImageView imageView, String arg1, boolean isLoadSuccess, Bitmap
            // arg3) {
            //// if(isLoadSuccess){
            //// imageView.setBackgroundDrawable(new BitmapDrawable(arg3));
            //// }
            // }
            //
            // @Override
            // public void onProcessChange(ImageView arg0, String arg1, long arg2, long arg3) {
            // // TODO Auto-generated method stub
            //
            // }
            // });

            ImageLoader.getInstance().displayImage(data.getBigimg(), imageView, ImageLoadUtil.build);

            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // Toast.makeText(mContext, "header", 0).show();

                }
            });

            container.addView(view);

            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(data.getUrl())) {
                        Intent intent = new Intent(getActivity(), WebBrowserActivity.class);
                        intent.putExtra(WebBrowserActivity.TITLE, data.getTitle());
                        intent.putExtra(WebBrowserActivity.URL, data.getUrl());
                        getActivity().startActivity(intent);
                    }
                }
            });

            return view;
        }

    }

    private ScheduledExecutorService scheduledExecutorService;
    private int pagerSize;
    public int currentItem;
    private static final int delayTime = 3;

    private void startPagerTask() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 每隔2秒钟切换一张图片
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), delayTime, delayTime, TimeUnit.SECONDS);
        mHeaderViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentItem = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    private class ViewPagerTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % pagerSize;
            handler.obtainMessage().sendToTarget();
        }
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mHeaderViewPager.setCurrentItem(currentItem);
        }
    };

}
